package com.lindroy.androidplayer.viewmodels

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.switchMap
import com.lindroy.androidplayer.utils.mapSingle
import com.lindroy.androidplayer.utils.switchMapSingle
import com.lindroy.androidplayer.R
import com.lindroy.androidplayer.logic.network.repository.Repository
import com.lindroy.androidplayer.utils.SingleLiveEvent
import com.lindroy.lib_utils.extensions.getResString

/**
 * @author Lin
 * @date 2022/1/29
 * @function
 */
class RegisterViewModel : ViewModel() {

    private val _registerLiveData = SingleLiveEvent<Unit>()

    private val _registerIllegalMessage = SingleLiveEvent<String>()

    private val _toLoginLiveData = SingleLiveEvent<Unit>()

    val registerLiveData = _registerLiveData.switchMapSingle {
        Repository.register(
            userName.value.orEmpty(),
            password.value.orEmpty(),
            rePassword.value.orEmpty()
        )
    }

    val userName = MutableLiveData<String>()

    val password = MutableLiveData<String>()

    val rePassword = MutableLiveData<String>()

    val toLoginLiveData = _toLoginLiveData.mapSingle { }

    val registerIllegalMessage = _registerIllegalMessage.mapSingle { it }

    fun onRegisterClick() {
        if (userName.value.orEmpty().isEmpty()) {
            _registerIllegalMessage.postValue(getResString(R.string.tip_user_name_null))
            return
        }

        if (password.value.orEmpty().isEmpty()) {
            _registerIllegalMessage.postValue(getResString(R.string.tip_pwd_null))
            return
        }

        if (rePassword.value.orEmpty().isEmpty()) {
            _registerIllegalMessage.postValue(getResString(R.string.tip_different_pwd))
            return
        }
        _registerLiveData.postValue(Unit)
    }

    fun onToLoginPage() {
        _toLoginLiveData.postValue(Unit)
    }

}